package model

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

import "fmt"
import "time"

//爬取漫画日志表
type Log struct {
	ID         int64
	Manga_id   int64
	Chapter_id int64
	Site       string
	Code       string
	Title      string
	Url        string
}

//漫画主表
type Manga struct {
	Manga_id        int64 `gorm:"primary_key"`
	Title           string
	Code            string
	Altname         string
	Cover           string
	Summary         string
	Last_chapter_id float64
	Last_updated    int64
	Entry_time      int64
	Status          string
	Categories      string
	Language        string
	Author          string
	Artist          string
}

//章节数据表
type Chapter struct {
	Chapter_id  int64 `gorm:"primary_key"`
	Manga_id    int64
	Title       string
	No          float64
	Entry_time  int64
	Total_pages int64
}

//新建一个自己的结构来继承gorm.DB
type MyDb struct {
	*gorm.DB
}

//本地数据库名
var dbName = ".manga.db"

//连接数据库sqlite3,如果不存在会自己创建
func Open() *MyDb {
	db, err := gorm.Open("sqlite3", dbName)
	if err != nil {
		panic("failed to connect database")
	}

	return &MyDb{db}
}

//第一次运行初始化所有表
func (db *MyDb) First() bool {
	db.AutoMigrate(&Log{})
	db.AutoMigrate(&Manga{})
	db.AutoMigrate(&Chapter{})
	return true
}

func AddManga(manga Manga) bool {
	db := Open()
	defer db.Close()
	res := db.NewRecord(manga)
	db.Create(&manga)
	return res
}

func AddChapter(chapter Chapter) (Chapter, bool) {
	db := Open()
	defer db.Close()
	res := db.NewRecord(chapter)
	db.Create(&chapter)
	return chapter, res
}

func UpdateManga(manga_id int64) bool {
	db := Open()
	defer db.Close()

	var chapter Chapter
	var manga Manga

	db.Raw("SELECT MAX(no) as no FROM chapters WHERE manga_id = ?", manga_id).Scan(&chapter)

	db.Model(&manga).Updates(Manga{
		Last_chapter_id: chapter.No,
		Last_updated:    time.Now().Unix(),
	})

	return true
}

func AddLog(log Log) bool {
	db := Open()
	defer db.Close()
	res := db.NewRecord(log)
	db.Create(&log)
	return res
}

//根据code查找漫画，不存在返回0，存在返回id
func FindManga(code string) int64 {
	db := Open()
	defer db.Close()

	var manga Manga
	db.Select("Manga_id, title").Where("code = ?", code).First(&manga)
	if manga.Manga_id != 0 {
		fmt.Println("manga exist id:", manga.Manga_id, "title:", manga.Title)
	}
	return manga.Manga_id
}

//查看章节是否存在
func FindChapter(manga_id int64, no float64) int64 {
	db := Open()
	defer db.Close()

	var chapter Chapter
	db.Select("chapter_id").Where("manga_id = ? AND no = ?", manga_id, no).First(&chapter)
	if chapter.Chapter_id != 0 {
		fmt.Println("chapter exist!")
	}
	return chapter.Chapter_id
}

func (db *MyDb) Search() bool {
	// db.AutoMigrate(&Animal{})
	// var animal = Animal{Age: 99, Name: ""}
	// db.Create(&animal)
	return true
}
